// 双端队列解法

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }
        int[] res = new int[nums.length - k + 1];
        Deque<Integer> deque = new LinkedList<>();
        int index = 0;
        for (int i = 0; i < k; i++) {
            while (!deque.isEmpty() && (nums[i] > deque.peekLast())) {
                deque.removeLast();
            }
            deque.addLast(nums[i]);
        }
        res[index++] = deque.peekFirst();
        for (int i = k; i < nums.length; i++) {
            if (!deque.isEmpty() && nums[i - k] == deque.peekFirst()) {
                deque.removeFirst();
            }
            while (!deque.isEmpty() && (nums[i] > deque.peekLast())) {
                deque.removeLast();
            }
            deque.addLast(nums[i]);
            res[index++] = deque.peekFirst();
        }
        return res;
    }
}